package cn.kgc.ssm.service.Impl;

import cn.kgc.ssm.dto.UserPageDTO;
import cn.kgc.ssm.entity.User;
import cn.kgc.ssm.mapper.UserMapper;
import cn.kgc.ssm.service.UserService;
import cn.kgc.ssm.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/10/20
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result search(UserPageDTO userPageDTO) {
        Result result = new Result();
        try {
            // 使用分页插件实现分页功能
            PageHelper.startPage(userPageDTO.getPage(), userPageDTO.getLimit());
            List<User> users = userMapper.search(userPageDTO.getUsername(), userPageDTO.getCity());
            PageInfo<User> userPageInfo = new PageInfo<>(users);
            //获取总条数
            long total = userPageInfo.getTotal();
            // 封装返回数据
            result.setCode(0);
            result.setMsg("查询成功");
            result.setCount(total);
            result.setData(users);

        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("查询失败");
        }
        return result;
    }

    @Override
    public Result add(User user) {
        Result result = new Result();
        try {
            userMapper.add(user);
            result.setCode(0);
            result.setMsg("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("添加失败");
        }
        return result;
    }

    @Override
    public Result update(User user) {
        Result result = new Result();

        try {
            userMapper.update(user);
            result.setCode(0);
            result.setMsg("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("更新失败");
        }
        return result;
    }

    @Override
    public Result deleteMore(String[] idArray) {
        Result result = new Result();
        try {
            userMapper.deleteMore(idArray);
            result.setCode(0);
            result.setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("删除失败");
        }
        return result;
    }
}
